package ro.isdc.training.ejb3.course.dao.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ro.isdc.training.ejb3.course.dao.CourseDAO;
import ro.isdc.training.ejb3.course.domain.Course;
import ro.isdc.training.ejb3.course.domain.CourseId;

/**
 * Course Data Access Object Bean Implementation.
 * 
 * @author Andrei Chirila
 */
@Stateless
@Local(CourseDAO.class)
public class CourseDAOBean implements CourseDAO {

  @PersistenceContext
  private EntityManager entityManager;

  /**
   * {@inheritDoc}
   */
  public Course findCourseByIdentification(final CourseId courseId) {
    List<Object> paramValuesList = new ArrayList<Object>();
    List<String> paramNamesList = new ArrayList<String>();

    String sql = "select c from Course c";
    if (courseId != null) {
      if (courseId.getEntityId() > 0) {
        sql += " where c.entityId = :entityId";
        paramNamesList.add("entityId");
        paramValuesList.add(courseId.getEntityId());
      } else {
        sql += " where c.courseName = :courseName";
        paramNamesList.add("courseName");
        paramValuesList.add(courseId.getCourseName());
      }
    }

    return (Course) entityManager.createQuery(sql).setParameter(
        paramNamesList.get(0), paramValuesList.get(0)).getSingleResult();
  }

}
